package com.bicon.botu.mall.goods.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.core.base.common.BusinessException;
import com.bicon.botu.mall.goods.entity.TraceElement;
import com.bicon.botu.mall.goods.mapper.TraceElementMapper;
import com.bicon.botu.mall.goods.service.ITraceElementService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 微量元素 服务实现类
 * </p>
 *
 * @author 孙永刚
 * @since 2017-07-21
 */
@Service
public class TraceElementServiceImpl extends ServiceImpl<TraceElementMapper, TraceElement> implements ITraceElementService {

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public boolean addTraceElement(String element, String productId, int tracePlanId) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(element)) {
            return false;
        }
        List<TraceElement> list = JSONObject.parseArray(element, TraceElement.class);
        List<TraceElement> newList = new ArrayList<>(list.size());
        TraceElement temp;
        for (int i = 0; i < list.size(); i++) {
            temp = list.get(i);
            temp.setTracePlanId(tracePlanId);
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(temp.getId())) {
                temp.setSort(i + 1);
                temp.preUpdate();
            } else {
                temp.setSort(i + 1);
                temp.setProductId(productId);
                temp.preInsert();
            }
            newList.add(temp);
        }
        return insertOrUpdateBatch(newList);
    }
}
